
# -*- coding: UTF-8 -*-
import mqtt
import ujson
import utime as time
import _thread


# 定义subcribe的回调函数
def on_subcribe(topic,payload):
    global client
    global g_qos,g_post_topic
    print("on_subcribe: topic is:" + topic)
    print("on_subcribe: payload is:" + payload)
    #平台下发的信息
    cloudmsg = ujson.loads(payload)
    print(cloudmsg)
    # 根据下发的信息进行 相应的处理
    

                


def mqttloop_func(delay, id):
    global client
    global mqtt_state
    global g_clientId,g_userName,g_password,g_mqttAddr ,g_port,g_heartBeat,g_get_topic,g_qos,g_post_topic
    while True:
        time.sleep_ms(delay)
        # print('Running thread %d'%id)
        # print("mqtt_state:",mqtt_state)
        ret = client.loop(1000)
        # print('client ret ={}'.format(ret))
        if ret < 0:
            print('------------------mqtt disconnect!')
            client.disconnect()
            mqtt_reconnect(g_clientId,g_userName,g_password,g_mqttAddr ,g_port,g_heartBeat,g_get_topic,g_post_topic,g_qos)
        else:
            pass

def mqtt_reconnect(clientId,userName,password,mqttAddr,port,heartBeat,get_topic,post_topic,qos):
    global client
    global mqtt_state
    global g_clientId,g_userName,g_password,g_mqttAddr ,g_port,g_heartBeat,g_get_topic,g_post_topic,g_qos

    g_clientId=clientId
    g_userName=userName
    g_password=password
    g_mqttAddr=mqttAddr
    g_port=port
    g_heartBeat=heartBeat
    g_get_topic=get_topic
    g_post_topic=post_topic
    g_qos=qos

    client = mqtt.client(g_clientId)
    client.on_subcribe(on_subcribe)

    # 设置用户名和密码
    client.username_pw_set(g_userName,g_password)
    # 建立mqtt连接
    ret = client.connect(g_mqttAddr,g_port,g_heartBeat)
    if ret == 0:
        mqtt_state = 1
    # 订阅服务
    client.subscribe(g_get_topic,g_qos)


def mqtt_connect(clientId,userName,password,mqttAddr,port,heartBeat,get_topic,post_topic,qos):

    mqtt_reconnect(clientId,userName,password,mqttAddr,port,heartBeat,get_topic,post_topic,qos)
    #创建mqtt接收数据任务，1s一次
    _thread.start_new_thread(mqttloop_func,(1000, 1))


def update(key,value):
    data={}
    data[key]=value
    #上报 格式 可以参考这句话
    #{"id":"2","version":"1.0","params":{"LBS": "(120.7396227,31.2741778)"},"sys":{"ack":1}}
    send_data = {
        "id":"1",
        "version":"1.0",
        "params":data,
        "sys":{"ack":1}
    }
    MSG = ujson.dumps(send_data)
    # 发布服务
    client.publish(g_post_topic,MSG,g_qos)




